package com.haynes.social.service.Impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haynes.social.common.Result;
import com.haynes.social.entity.User;
import com.haynes.social.mapper.UserMapper;
import com.haynes.social.service.IUserService;
import com.haynes.social.util.IdGeneration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import static com.haynes.social.util.RedisKey.USER_LOGIN_CODE_KEY;

/**
 * @Author Haynes
 * @Date 2023/5/26 21:16
 * @PackageName:com.haynes.store.service.Impl
 * @ClassName: UserServiceImpl
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Result<User> login(Map<String, Object> map) {
//        获取用户的手机号
        String phone = map.get("phone").toString();
//        获取用户输入的验证码
        String code = map.get("code").toString();

        String key=USER_LOGIN_CODE_KEY+phone;

//        比对缓存中的验证码
        String cacheCode = redisTemplate.opsForValue().get(key).toString();
        if (!(cacheCode.equals(code))){
            return Result.error("验证码输入错误");
        }
//        查询数据库是否存在对应的用户
        User user = this.query().eq("phone", phone).one();
        if (user==null){
//            为空则创建新用户
            user = new User();
            user.setId(IdGeneration.getUUID());
            user.setPhone(phone);
            user.setNickname("social"+phone);
            user.setAvatar("placeholder.jpg");
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            this.save(user);
        }
//        登录完成后删除redis中的验证码
        redisTemplate.delete(key);
        return Result.success(user);
    }
}
